/**
 * weapp-js
 * https://code.aliyun.com/jionglee/weapp_base.git
 * Copyright@ 2020 Motigo, Inc.
 * 
 */
// weapp_base 框架自身网络的接口调用封装

export default {
    HOST: 'https://weapp.motimaster.com',
    appid: '',
    openid: '',
    unionid: '',
    session_id: '',
    get(path, params, enable_cache, expire_in) {
        enable_cache;
        expire_in;
        return this._request('GET', path, params);
    },
    post(path, params) {
        return this._request('POST', path, params);
    },
    put(path, params) {
        return this._request('PUT', path, params);
    },
    delete(path, params) {
        return this._request('DELETE', path, params);
    },
    // 更新用户数据，由session.js调用（不太合理）
    _update_session(session_id, appid, openid, unionid) {
        this.session_id = session_id;
        this.appid = appid;
        this.openid = openid;
        this.unionid = unionid;
    },
    _request(method, path, params) {
        const accountInfo = wx.getAccountInfoSync();
        this.appid = accountInfo.miniProgram.appId;
        return new Promise((resolve, reject) => {
            wx.request({
                method: method,
                timeout: 10000,
                header: {
                    'content-type': 'application/json',
                    'appid': this.appid,
                    'openid': this.openid,
                    'unionid': this.unionid,
                    'session': this.session_id
                },
                url: this.HOST + path,
                data: params,
                success(res) {
                    if (res.data.ret == 0) {
                        resolve(res.data.data);
                    } else {
                        reject(res.data);
                    }
                },
                fail(err) {
                    reject(err)
                }
            })
        });
    }
}